package com.cms.service.menu;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.mock.base.util.CollectionUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MenuServiceImpl implements MenuService {

	@Override
	public List<Map<String,Object>> getMenuListByUserId() {
		
		//获取属于用户的第一层菜单(level为1)
        String querySQL = " SELECT * FROM cms_menu WHERE level = 1 order by display_order asc ";

        List<Record> menuList0 = Db.find(querySQL);
		if (CollectionUtil.isEmpty(menuList0)) return null;

		
		//查询一级菜单下面的子菜单
		List<Map<String,Object>> returnList = new ArrayList<>();
		for (Record parent : menuList0) {
			returnList.add(recurseMenu(parent));
		}
		
		return returnList;
	}
	
	
	private Map<String,Object> recurseMenu(Record parent0) {
		Long parentId = parent0.getLong("id");
		String sql = "select * from cms_menu where parent_id = ? order by display_order asc";
		List<Record> childList = Db.find(sql, parentId);
		List<Map<String,Object>> returnList = new ArrayList<>();
		if (CollectionUtil.isEmpty(childList)) {
			Map<String,Object> menuMap = record2Map(parent0);
			menuMap.put("children", returnList);
			return menuMap;
		}else {
			Map<String,Object> menuMap = record2Map(parent0);
			for (Record parent : childList) {
				returnList.add(recurseMenu(parent));
			}
			menuMap.put("children", returnList);
			return menuMap;
		}
	}
	
	private Map<String,Object> record2Map(Record record) {
		
		Map<String,Object> menuMap = new HashMap<>();
		menuMap.put("id", record.get("id"));
		menuMap.put("name", record.get("name"));
		menuMap.put("url", record.get("url"));
		menuMap.put("level", record.get("level"));
		menuMap.put("micon",record.get("micon"));
		menuMap.put("parentId", record.get("parent_id"));
		return menuMap;
	}

}
